package cn.wit.test;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("初始化");
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		//不要判断登陆界面
		String uri = ((HttpServletRequest) request).getRequestURI();
		if(uri.contains("form.html")||uri.contains("login")) {
			chain.doFilter(request, response);
			return;
		}
		
		//如果session有用户名，说明登陆过，那么请求就直接放行
		//如果没有，那么久直接返回登陆界面
		HttpSession session = ((HttpServletRequest) request).getSession();
		
		String user = (String) session.getAttribute("user");
		
		if(user == null) {
			
			((HttpServletResponse) response).sendRedirect("form.html");
			
		}else {
			
			//如果登陆呢，放行
			chain.doFilter(request, response);
			
		}
		
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("销毁");
		
	}

}
